<template>
  <div class="scenicList-wrapper">
    <section class="app-container">
      <el-row class="inputform" v-if="configQueryWhere.length > 0">
        <query-from
          ref="queryfrom"
          :showQueryWhere="configQueryWhere"
          v-if="fromInfo.layoutitemlist !== undefined"
          :data="fromInfo.layoutitemlist[0].widgetForm"
        ></query-from
      ></el-row>
      <el-row class="inputform" style="margin-top: 10px;">
        <el-col :span="20">
          <el-button type="primary" @click="loadData(1)">查询</el-button>
          <el-button @click="Resetfromdata()">重置</el-button>
          <el-button type="primary" @click="addfrom">新增</el-button>
          <el-button type="primary" @click="exportExlce()">导出</el-button>
          <el-button
            type="primary"
            @click="butfromreport()"
            v-if="isShowButReport"
            >报表统计</el-button
          >
        </el-col>
        <el-col :span="4" style="text-align: right;">
          <el-dropdown
            @command="handleCommand"
            trigger="click"
            style="margin-top: 10px;
    margin-bottom: auto;"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-setting" style="font-size: 16px;" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="q">设置条件</el-dropdown-item>
              <el-dropdown-item command="c">设置列</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
      <div class="ant-table_container">
        <a-table
          bordered
          :data-source="tableData"
          :columns="tableColumns"
          :pagination="false"
          :scroll="{ x: 2000 }"
        >
          <div
            v-for="item in scopedSlots"
            v-bind:key="item.dataid"
            slot-scope="text, record"
            :slot="item.dataid"
            v-html="getcelvalue(item.type, record, text)"
          ></div>
          <div slot="operation" slot-scope="text, record">
            <a
              class="margin-a"
              href="javascript:;"
              style="margin-right: 5px;"
              @click="viewfrom(record)"
              >查看</a
            >
          </div>
        </a-table>
      </div>
      <div class="ant-table_footer">
        <a-pagination
          :loading="isloading"
          v-model="pagination.currnet"
          :default-current="1"
          :total="pagination.total"
          show-quick-jumper
          @change="handleTableChange"
          @showSizeChange="showSizeChange"
          :pageSize="pagination.pagesize"
          show-size-changer
        />
      </div>
    </section>
    <el-drawer
      title="设置列"
      :visible.sync="showConfigCel"
      :direction="direction"
    >
      <div style="margin:10px">
        <el-checkbox-group v-model="configshowcel" size="small">
          <el-checkbox
            border
            v-for="(item, index) in allcels"
            :key="item.value + index"
            :label="item.value"
            >{{ item.label }}</el-checkbox
          >
        </el-checkbox-group>
        <el-button type="primary" @click="saveShowCelNames">保存</el-button>
        <el-button type="info" @click="configshowcel = []">重置</el-button>
      </div>
    </el-drawer>
    <el-drawer
      title="设置查询条件"
      :visible.sync="showConfigQueryWhere"
      :direction="direction"
    >
      <div style="margin:10px">
        <el-checkbox-group v-model="configQueryWhere" size="small">
          <el-checkbox
            border
            v-for="(item, index) in allcels"
            :key="item.value + index"
            :label="item.value"
            >{{ item.label }}</el-checkbox
          >
        </el-checkbox-group>
        <el-button type="primary" @click="saveConfigQueryWhere">保存</el-button>
        <el-button type="info" @click="configQueryWhere = []">重置</el-button>
      </div>
    </el-drawer>
    <a-modal
      v-model="visible"
      wrapClassName="ant-modal-centered dialog is-portal-color window-max hiddenoverflow"
      width="100%"
      :zIndex="99"
      :footer="null"
      :bodyStyle="{ padding: '0px' }"
      :closable="false"
      :destroyOnClose="true"
    >
      <fromreport :fromInfo="fromInfo" @close="winclose"></fromreport>
    </a-modal>
  </div>
</template>
<script>
import QueryFrom from '@/components/formdesign/queryFrom.vue'
import { getFromInfo, saveConfigQueryJson } from '@/api/tappfrom.js'
import { saveConfigShowCelNames } from '@/api/packageInterface.js'
import { apiComm, ExportExlce } from '@/api/index'
import fromreport from '@/views/fromdesign/fromreport.vue'
export default {
  data() {
    return {
      queryparam: { fromname: '' },
      scopedSlots: [],
      apicode: '',
      fromInfo: {},
      fromcontrolList: [],
      tableData: [],
      pagination: {
        currnet: 1,
        pagesize: 8,
        total: 0
      },
      tableColumns: [],
      isloading: false,
      fromid: '',
      showConfigCel: false,
      direction: 'rtl',
      configshowcel: [],
      allcels: [],
      showConfigQueryWhere: false,
      configQueryWhere: []
    }
  },
  components: { QueryFrom, fromreport },
  methods: {
    viewfrom(row) {
      window.open(`/viewfrom?fromid=${this.fromid}&tablefid=${row.fid}`)
      // this.$router.push({
      //   path: `/Flow/viewfrom?fromid=${this.fromid}&tablefid=${row.fid}`
      // })
    },
    addfrom() {
      window.open(`/viewfrom?fromid=${this.fromid}`)
    },
    LoadQueryWhere() {
      getFromInfo(this.fromid).then(res => {
        this.fromInfo = JSON.parse(res.data.fromdesignjson)
        this.configQueryWhere = []
        if (
          res.data.queryJson !== undefined &&
          res.data.queryJson !== null &&
          res.data.queryJson !== ''
        ) {
          this.configQueryWhere = res.data.queryJson.split(';')
        }
        const controlList = this.fromInfo.layoutitemlist[0].widgetForm.list[0]
          .columns[0].list
        for (let i = 0; i < controlList.length; i++) {
          const controlItem = controlList[i]
          switch (controlItem.type) {
            case 'input':
              break
            case 'textarea':
              break
            case 'select':
              this.scopedSlots.push({
                dataid: controlItem.options.filed,
                type: controlItem.type
              })
              break
            case 'date':
              break
            case 'radio':
              this.scopedSlots.push({
                dataid: controlItem.options.filed,
                type: controlItem.type
              })
              break
            case 'checkbox':
              this.scopedSlots.push({
                dataid: controlItem.options.filed,
                type: controlItem.type
              })
              break
            case 'switch':
              this.scopedSlots.push({
                dataid: controlItem.options.filed,
                type: controlItem.type
              })
              break
            case 'slider':
              break
            case 'colorpicker':
              this.scopedSlots.push({
                dataid: controlItem.options.filed,
                type: controlItem.type
              })
              break
            case 'editor':
              break
            case 'rate':
              break
            case 'inputnumber':
              break
            case 'timepicker':
              break
            case 'upFilesComp':
              this.scopedSlots.push({
                dataid: controlItem.options.filed,
                type: controlItem.type
              })
              break
            default:
              break
          }
        }
        this.loadData(1)
      })
    },
    loadData(pagenum) {
      if (this.isloading) {
        return
      }
      const param = this.getqueryparam()
      param.page = pagenum !== undefined ? pagenum : this.pagination.currentpage
      param.rows = this.pagination.pagesize
      this.isloading = true
      this.configshowcel = []
      this.allcels = []
      apiComm(this.apicode, param).then(res => {
        this.isloading = false
        if (res.code === 0 && res.success) {
          if (
            res.data.showCelNames !== null &&
            res.data.showCelNames !== undefined
          ) {
            this.configshowcel = res.data.showCelNames.split(';')
          }
          this.tableColumns = []
          this.tableColumns.push({
            title: '操作',
            dataIndex: 'operation',
            width: 150,
            scopedSlots: { customRender: 'operation' },
            align: 'center'
          })
          for (let i = 0; i < res.data.columns.length; i++) {
            this.allcels.push({
              label: res.data.columns[i].headname,
              value: res.data.columns[i].bindname
            })
            const item = {
              title: res.data.columns[i].headname,
              dataIndex: res.data.columns[i].bindname,
              align: 'center'
            }
            if (
              this.scopedSlots.filter(
                ee => ee.dataid === res.data.columns[i].bindname
              ).length >= 0
            ) {
              item.scopedSlots = {
                customRender: res.data.columns[i].bindname
              }
            }
            if (
              this.configshowcel.length === 0 ||
              this.configshowcel.indexOf(res.data.columns[i].bindname) >= 0
            ) {
              this.tableColumns.push(item)
            }
          }
          this.pagination.current = param.page
          this.pagination.total = res.totalcount
          this.tableData = res.data.list
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    exportExlce() {
      const param = this.getqueryparam()
      ExportExlce(this.apicode, param).then(res => {
        if (res.code !== 0) {
          const blob = new Blob([res.data], {
            type:
              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
          })
          if (window.navigator.msSaveBlob) {
            window.navigator.msSaveBlob(
              blob,
              Date.parse(new Date()) +
                '_' +
                Math.ceil(Math.random() * 99999) +
                '.xls'
            )
          } else {
            const downloadElement = document.createElement('a')
            const href = window.URL.createObjectURL(blob)
            downloadElement.href = href
            downloadElement.download =
              Date.parse(new Date()) +
              '_' +
              Math.ceil(Math.random() * 99999) +
              '.xls'
            document.body.appendChild(downloadElement)
            downloadElement.click()
            document.body.removeChild(downloadElement)
            window.URL.revokeObjectURL(href)
          }
        } else {
          this.executeResult = res
        }
      })
    },
    handleTableChange(pagination) {
      this.loadData(pagination)
    },
    showSizeChange(page, pageSize) {
      this.pagination.pagesize = pageSize
      this.loadData(1)
    },
    getcelvalue(type, record, text) {
      try {
        if (text === null || text === undefined || text === '') {
          return text
        }
        let valuejson = {}
        switch (type) {
          case 'input':
            break
          case 'textarea':
            break
          case 'select':
            if (text.indexOf('[') >= 0) {
              valuejson = JSON.parse(text)
              return valuejson.join(';')
            }
            break
          case 'date':
            break
          case 'radio':
            if (text.indexOf('[') >= 0) {
              valuejson = JSON.parse(text)
              return valuejson.join(';')
            }
            break
          case 'checkbox':
            if (text.indexOf('[') >= 0) {
              valuejson = JSON.parse(text)
              return valuejson.join(';')
            }
            break
          case 'switch':
            return text === '1' ? '是' : '否'
          case 'slider':
            break
          case 'colorpicker':
            break
          case 'editor':
            break
          case 'rate':
            break
          case 'inputnumber':
            break
          case 'timepicker':
            break
          case 'upfilesComp':
            if (text.indexOf('[') >= 0) {
              valuejson = JSON.parse(text)
              let imgstr = ''
              for (let i = 0; i < valuejson.length; i++) {
                imgstr =
                  imgstr +
                  ` <img src="${valuejson[i].url}" width="20" height="20"/>`
              }
              return imgstr
            }

          default:
            break
        }
      } catch {
        console.log(text)
      }
      return text
    },
    handleCommand(command) {
      switch (command) {
        case 'q':
          this.showConfigQueryWhere = true
          break
        case 'c':
          this.showConfigCel = true
          break
        default:
          break
      }
    },
    saveShowCelNames() {
      if (this.configshowcel.length === 0) {
        this.$message.error('请选择显示的列！')
      } else {
        saveConfigShowCelNames({
          callMethodCodeName: this.apicode,
          showCelNames: this.configshowcel.join(';')
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('设置成功！')
            this.loadData(1)
          }
        })
      }
    },
    saveConfigQueryWhere() {
      saveConfigQueryJson({
        fid: this.fromid,
        queryJson: this.configQueryWhere.join(';')
      }).then(res => {
        if (res.code === 0) {
          if (this.$refs.queryfrom !== undefined) {
            this.$refs.queryfrom.Resetfromdata()
          }
          this.showConfigQueryWhere = false
          this.$message.success('设置成功！')
          this.loadData(1)
        }
      })
    },
    getqueryparam() {
      if (this.$refs.queryfrom !== undefined) {
        return this.$refs.queryfrom.getfromdata()
      }
      return {}
    },
    Resetfromdata() {
      if (this.$refs.queryfrom !== undefined) {
        return this.$refs.queryfrom.Resetfromdata()
      }
    },
    butfromreport() {
      this.visible = true
    },
    winclose() {
      this.visible = false
    }
  },
  computed: {},
  created() {
    this.fromid = this.$route.query.fromid
    this.apicode = this.$route.query.questionName + '.querylist'
    this.LoadQueryWhere()
  }
}
</script>
<style scoped>
.el-checkbox.is-bordered.el-checkbox--small {
  margin-bottom: 10px;
}
.inputform div:first-child {
  height: 40px;
  margin-bottom: 10px;
}
.inputform button {
  margin-left: 5px;
  margin-right: 5x;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
